package com.etoak.handler;

import com.etoak.exception.CustomException;
import com.etoak.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 处理全局异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理校验异常
     */
    @ExceptionHandler
    public ResultVO<Object> handle(MethodArgumentNotValidException e){
        log.error(e.getMessage(),e);
        String message = e.getAllErrors().stream().map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(";"));
        return ResultVO.failed(message);
    }


    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler
    public ResultVO<Object> handle(CustomException e){
        log.error(e.getMessage(),e);
        return ResultVO.failed(e.getMessage());
    }

    /**
     * 处理其他异常--500  系统异常
     */
    @ExceptionHandler
    public ResultVO<Object> handle(Exception e){
        log.error(e.getMessage(),e);
        return ResultVO.failed();
    }
}